package club.pchome.controller;

import club.pchome.constant.Constant;
import club.pchome.dto.Result;
import club.pchome.ex.ServiceException;
import club.pchome.ex.code.BaseResponseCode;
import club.pchome.model.User;
import club.pchome.service.UserService;
import club.pchome.utils.*;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


/**
 * 用户处理
 * @author Watler
 */
@Api(tags = {"用户处理"})
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController{

    @Autowired
    UserService userService;

    @ApiOperation(value = "获取用户信息")
    @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "id") })
    @GetMapping("/userInfo")
    public User userInfo(Integer id) throws Exception {
        TUtil.checkObj("id不能为空" , id);
        return userService.userInfo(id);
    }

    @ApiOperation(value = "注册用户")
    @PostMapping("/regUser")
    public Result<String> regUser(HttpServletRequest request, User user, String imgCode) throws Exception {
        TUtil.checkObj(new String[] {"用户名不能为空" , "密码不能为空"}, user.getLoginName(), user.getPasswd());
        //获取图形验证码token
        String CAPTCHA = getCookies("CAPTCHA");
        String cookieToken = redisUtil.get(CAPTCHA).toString();
        if(!cookieToken.equals(imgCode)){
            throw new ServiceException(BaseResponseCode.CAPTCHA_PASS_CODE);
        }

        //获取浏览器信息
        String ua = request.getHeader("User-Agent");
        IpUtil ipUtil = new IpUtil();
        String ip = ipUtil.getIpAddr(request);

        user.setDevice(ua);
        user.setLoginIp(ip);

        boolean b = userService.isTrue(user);
        if(b){
            throw new ServiceException(BaseResponseCode.USER_REG_ERROR);
        }
        int state = userService.regUser(user);
        if(state > 0){
            log.info("regUser : {} 注册成功", user.getLoginName());
            return Result.initSuccessResult("注册成功");
        }
        log.info("regUser : {} 注册失败 , 失败原因, 不详哈哈哈哈哈", user.getLoginName());
        throw new ServiceException(BaseResponseCode.USER_REG_FAILURE);
    }

    @ApiOperation(value = "登录用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "账号(手机号)", required = true),
            @ApiImplicitParam(name = "passwd", example = "123456", value = "密码", required = true),
            @ApiImplicitParam(name = "imgCode", value = "图形验证码", required = true),
    })
    @PostMapping("/login")
    public Result<User> loginUser(HttpServletRequest request, String username , String passwd , String imgCode) throws Exception {
        TUtil.checkObj(new String[] {"用户名不能为空" , "密码不能为空" , "验证码"}, username, passwd, imgCode);
        //获取图形验证码token
        String CAPTCHA = getCookies("CAPTCHA");
        String cookieToken = redisUtil.get(CAPTCHA).toString();
        if(!cookieToken.equals(imgCode)){
            log.error("图形验证码错误: 操作人: {}" , username);
            throw new ServiceException(BaseResponseCode.CAPTCHA_PASS_CODE);
        }

        //获取浏览器信息
        String ua = request.getHeader("User-Agent");
        User login = userService.loginUser(username , DigestUtil.md5Hex(passwd + Constant.MD5_USER_KEY) , ua);
        if (null == login) {
            throw new ServiceException(BaseResponseCode.USER_LOGIN_ERROR);
        }
        log.info("-----------------user:{}--------------------" ,login.getId());
        if(ua.equals(login.getDevice())){
            log.info("ua_info : 设备使用一致.");
        }else {
            log.info("ua_info : 新设备接入.");
        }

        // 登录成功,生成key
        JwtToken jwtToken = new JwtToken();
        jwtToken.setUserId(login.getId());
        String token = JwtUtils.createToken(jwtToken);
        log.info("ACCESS_TOKEN:{}" , token);
        String uuid = IdUtil.simpleUUID();
        if(redisUtil.hasKey("ACCESS_TOKEN:"+ uuid)){
            redisUtil.expire("ACCESS_TOKEN:"+ uuid , 60 * 60 * 2);
        }else {
            redisUtil.set("ACCESS_TOKEN:"+ uuid , token , 2 *  60 * 60);
        }
        login.setUid(uuid);
        log.info("-----------------end--------------------");
        return Result.initSuccessResult(login);
    }

    /**
     * 验证Token是否失效
     * @param tokenKey
     * @param userToken
     * @return
     */
    @PostMapping("/isTokenExpire")
    public Result<String> isTokenExpire(String tokenKey, String userToken) throws ServiceException {

        //首先判断token是否存在
        if(redisUtil.hasKey("ACCESS_TOKEN:"+tokenKey)){
            //2.获取缓存过期时间
            long tokenExpire = redisUtil.getExpire("ACCESS_TOKEN:"+tokenKey);
            logger.info("tokenExpire : " + tokenExpire);
            //2. 获取 token 签名信息
            String accessToken = redisUtil.get("ACCESS_TOKEN:"+tokenKey).toString();

            //如果不一致
            if(!accessToken.equals(userToken)){
                logger.info("账户已在另一个设备登录");
                throw new ServiceException(BaseResponseCode.USER_ONLY_LOGIN);
            }

            return Result.initSuccessResult(""+System.currentTimeMillis());
        }



        //3. 验证签名
//        JwtUtils
//        ACCESS_TOKEN.


        return Result.initFailureResult(20005 , "");
    }
}



